var over = 0;
var status = 0;   // 0: 编辑 1： 增加
var urlFetchById = parent.basePath + "/master/department/fetchByKey.html";
var urlSave = parent.basePath + "/master/department/save.html";
var urlDelete = parent.basePath + "/master/department/delete.html";

var thisPage = {
    first: 0,
    //得到部门信息数据
    GetEntityData: function () {
        var item = {};
        item['departmentId'] = ($("#id").val().length > 0) ? $("#id").val() : 0;
        item['parentId'] = ($("#ParentId").val().length > 0) ? $("#ParentId").val() : 0;
        item['orderNo'] = $.trim($("#OrderNo").val());
        item['departmentName'] = $.trim($("#DepartmentName").val());
        item['description'] = formatNullInputValue($.trim($("#Description").val()));

        return JSON.stringify(item);
    },
    // 初始化页面,得到树形节点数据
    OnPageLoad: function () {
        // 初始化树形控件
        $('#treeContent').jstree({
            "core": {
                "animation": 200,
                "multiple": false,
                "themes": {
                    "responsive": true,
                    "dots": false,
                    "icons": true
                },
                "check_callback": function (operation, node, node_parent, node_position, more) {
                    /*if (more && more.dnd && more.pos !== node_position) {
                     return false;
                     }
                     if (operation === "move_node" || operation === "copy_node") {
                     if (this.get_node(node).parent === this.get_node(node_parent).id) {
                     return false;
                     }
                     }*/
                    return true;
                },
                "data": {
                    'dataType': 'JSON',
                    'contentType': "application/json; charset=utf-8",
                    'type': "GET",
                    'url': parent.basePath + '/master/department/tree.html',
                    'data': function (node) {
                        var _nodeId = node.id === '#' ? -1 : (node.id === 'j1_1' ? 0 : node.id);
                        return {'parentKey': _nodeId, 'isPopupWnd': 0, 'isAdministrator': 1};
                    },
                    'complete': function () {
                        if (thisPage.first === 0) {
                            // 打开根节点
                            setTimeout(function () {
                                var ref = $.jstree.reference('treeContent');
                                var _obj = $("#j1_1");
                                ref.open_node(_obj);
                                ref.select_node(_obj);
                                thisPage.first = 1;
                                $('#loading').hide();
                            }, 500);
                        }
                    }
                }
            },
            "plugins": ["dnd", "contextmenu", "types", "wholerow"],
            "types": {
                "#": {"max_depth": -1, "max_children": -1, "valid_children": ["root"]},
                "root": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/Images/Tree/root.png", "valid_children": -1},
                "default": {"max_depth": -1, "max_children": -1, "valid_children": -1},
                "leaf": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/Images/Tree/folder_close.png", "valid_children": -1},
                "trash": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/Images/Tree/trash.png", "valid_children": -1}
            },
            "dnd": {
                "copy": false
            },
            "contextmenu": {
                "items": {
                    "create": {
                        "label": "新建部门",
                        "icon": parent.basePath + "/Images/Tree/add.png",
                        "action": function (data) {
                            var inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                            //dialog.show({"title": "新建“" + obj.text + "”的子菜单", url: "/accountmanage/createMenu?id=" + obj.id, height: 280, width: 400});
                            thisPage.DoInsert();
                        }
                    },
                    "edit": {
                        "label": "编辑部门",
                        "icon": parent.basePath + "/Images/Tree/edit.png",
                        "action": function (data) {
                            var inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                            //dialog.show({"title": "编辑“" + obj.text + "”菜单", url: "/accountmanage/editMenu?id=" + obj.id, height: 280, width: 400});
                        },
                        "separator_after": true
                    },
                    "remove": {
                        "label": "删除部门",
                        "icon": parent.basePath + "/Images/Tree/delete.png",
                        "action": function (data) {
                            var inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                            // 如果有子节点就返回
                            //if ($(this._get_node(obj)).hasClass("folder"))
                            //    return;
                            showModal(333, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？', thisPage.OnDelete);
                        }
                    }
                }
            }
        });
        // 树形节点选择
        $('#treeContent').on('select_node.jstree', function (event, data) {
            // 清除错误状态
            thisPage.ClearForm();

            var ref = $.jstree.reference('treeContent');
            var _nodeIdOfSelected = data.node.id;
            /*
             // 如果是鼠标右键按下，则不做处理
             if (data.event !== undefined) {
             if (data.event.button === 2) {
             //ref.deselect_node (data.node); 
             return false;
             }
             }*/
            var _nodeOfSelected = $("#" + _nodeIdOfSelected);

            if ((_nodeIdOfSelected !== "j1_1") && (ref.get_type(_nodeOfSelected) !== "trash")) {
                $("#OperateMode").html("<i class='fa-all fa-fw fa-pencil-square-o'></i>【操作状态】：编辑");
                status = 0; // 设置编辑状态
                var _parentNodeId = ref.get_parent(_nodeOfSelected);
                var _parentNodeOfSelected = $("#" + _parentNodeId);
                $('#ParentDeptName').text(_parentNodeOfSelected.attr("fullName"));

                // 重新设置选择的结点ID
                _nodeIdOfSelected = _nodeIdOfSelected === "j1_1" ? 0 : _nodeIdOfSelected;
                $('#id').val(_nodeIdOfSelected);
                // 如果不是根节点，则取得相应的节点信息
                thisPage.FetchById(_nodeIdOfSelected);
            } else {
                // 如果是根节点，清空右边表单内容，准备下一个记录
                $("#OperateMode").html("");
                $('#ParentDeptName').text("");
                status = -1; // 设置为无效状态
            }
        });
        // 节点展开后，重新设置图标
        $('#treeContent').on('open_node.jstree', function (event, data) {
            var ref = $.jstree.reference('treeContent');
            var _nodeIdOfSelected = data.node.id;
            var _nodeOfSelected = $("#" + _nodeIdOfSelected);
            if (_nodeIdOfSelected !== "j1_1")
                if (ref.get_type(_nodeOfSelected) !== "trash") {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/Images/Tree/folder_open.png");
                }
        });
        // 节点收回后，重新设置图标
        $('#treeContent').on('close_node.jstree', function (event, data) {
            var ref = $.jstree.reference('treeContent');
            var _nodeIdOfSelected = data.node.id;
            var _nodeOfSelected = $("#" + _nodeIdOfSelected);
            if (_nodeIdOfSelected !== "j1_1")
                if (ref.get_type(_nodeOfSelected) !== "trash") {
                    ref.set_icon(_nodeOfSelected, parent.basePath + "/Images/Tree/folder_close.png");
                }
        });
        // 删除节点后，设置父节点图标
        $('#treeContent').on('delete_node.jstree', function (event, data) {
            var ref = $.jstree.reference('treeContent');
            var _nodeIdOfSelectedParent = data.parent;
            var _nodeOfSelectedParent = $("#" + _nodeIdOfSelectedParent);
            if (_nodeIdOfSelectedParent !== "j1_1") {
                if (ref.is_leaf(_nodeOfSelectedParent) === true) {
                    ref.set_icon(_nodeOfSelectedParent, parent.basePath + "/Images/Tree/folder_close.png");
                }
            }
        });
        // 树形结点打开后
        $('#treeContent').on('after_open.jstree', function (event, data) {
            var ref = $.jstree.reference('treeContent');
            // 选择该结点
            var _newNode = $("#" + $("#id").val());
            if (_newNode.length > 0) {
                ref.select_node(_newNode);
            }
        });
        // 拖动节点结束后的事件
        $('#treeContent').on('move_node.jstree', function (event, data) {
            if (data.old_parent !== data.parent) {
                var _parentId = data.parent === "j1_1" ? 0 : data.parent;
                var params = {};
                params['CatalogueId'] = parseInt(data.node.id);   // 选择的节点
                params['ParentId'] = parseInt(_parentId);         // 目标节点

                $.ajax({
                    type: "POST",
                    url: parent.basePath + '/master/department/changeParentCatalogue.html',
                    timeout: 30 * 1000,
                    data: JSON.stringify(params),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    beforeSend: function () {
                    }
                }).done(function (data) {
                    if (parseInt(data) > 0) {
                        ShowSuccessMessagePanel("所属部门改变成功。");
                    }
                }).fail(function (data) {
                    ajaxError(data, 1);
                }).always(function () {
                });
            }
        });
    },
    // 创建新结点
    NewNode: function () {
        var node = {};
        var li_attr = {};
        node['id'] = $("#id").val().toString();
        node['text'] = $.trim($("#DepartmentName").val().toString());
        node['type'] = "leaf";
        node['children'] = false;
        li_attr['fullName'] = $.trim($("#ParentDeptName").text()) + " → " + $.trim($("#DepartmentName").val());
        node['li_attr'] = li_attr;
        //return JSON.stringify(node);
        return node;
    },
    FetchById: function (nodeId) {
        $.ajax({
            type: "POST",
            url: urlFetchById,
            timeout: 30 * 1000,
            data: JSON.stringify(nodeId),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            $("#id").val(data.departmentId);                  //部门ID
            $("#ParentId").val(data.parentId);                //部门ID
            $("#OrderNo").val(data.orderNo);                  //部门编码
            $("#DepartmentName").val(data.departmentName);    //部门
            $("#Description").val(data.description);          //备注
        }).fail(function (data) {
            parent.ajaxError(data, 1);
        }).always(function () {
        });
    },
    //保存数据
    DoSave: function () {
        // 设置为无效状态
        if (parseInt(status) === -1) {
            showModal(330, 140, '系统信息', '', null, null, 4, "对不起，不能修改系统初始信息。");
            return false;
        }
        var ref = $.jstree.reference('treeContent');
        var sel = ref.get_selected()[0];
        if (sel === undefined) {
            showModal(330, 140, '系统信息', '', null, null, 4, "请选择部门。");
            return false;
        }

        if (!$("#mainForm").valid())
            return;

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: urlSave,
            timeout: 30 * 1000,
            data: thisPage.GetEntityData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                showLoadmask();
            }
        }).done(function (data) {
            if (parseInt(data) > 0) {
                switch (parseInt(status)) {
                    case 0: //  编辑
                        var _obj = $("#" + sel);
                        // 修改路径名
                        var _fullName = $.trim($("#ParentDeptName").text()) + " → " + $.trim($("#DepartmentName").val());
                        _obj.attr("fullName", _fullName);
                        ref.rename_node(_obj, $.trim($("#DepartmentName").val())); // 修改节点文字
                        break;
                    case 1: // 新增
                        $("#id").val(data);
                        var _obj = $("#" + sel);
                        // 增加树形节点
                        ref.create_node(_obj, thisPage.NewNode());
                        ref.load_node(_obj);
                        ref.open_node(_obj);
                        // 取消当前选择点
                        ref.deselect_node(_obj);
                        // 选择该结点
                        var _newNode = $("#" + data);
                        ref.select_node(_newNode);
                        status = 0; // 设置为编辑状态
                        break;
                }
                ShowSuccessMessagePanel("保存成功。");
            }
        }).fail(function (data) {
            parent.ajaxError(data, 1);
        }).always(function () {
            hideLoadmask();
        });
    },
    // 新增信息
    DoInsert: function () {
        var ref = $.jstree.reference('treeContent');
        var sel = ref.get_selected()[0];
        if (sel === undefined) {
            showModal(330, 140, '系统信息', '', null, null, 4, "请选择一个所属部门。");
            return;
        }
        var _nodeIdOfSelected = sel === "j1_1" ? 0 : sel;
        var _nodeOfSelected = $("#" + sel);
        if (ref.get_type(_nodeOfSelected) === "trash") {
            showModal(330, 140, '系统信息', '', null, null, 4, "不能增加系统回收站。");
            return;
        }
        status = 1; // 设置为新增状态

        // 清空表单内容，准备下一个记录
        thisPage.ClearForm();
        $("#OperateMode").html("<i class='fa-all fa-fw fa-status fa-pencil-square-o'></i>【操作状态】：增加部门");
        $('#ParentDeptName').text(_nodeOfSelected.attr("fullName"));
        $('#ParentId').val(_nodeIdOfSelected);
        $('#id').val("0");

        // 设置焦点
        $("#OrderNo").focus();
    },
    // 删除
    DoDelete: function () {
        var ref = $.jstree.reference('treeContent');
        var sel = ref.get_selected()[0];
        if (sel === undefined) {
            showModal(330, 140, '系统信息', '', null, null, 4, "请选择部门。");
            return false;
        }
        if (sel === "j1_1") {
            showModal(330, 140, '系统信息', '', null, null, 4, "不能删除公司名称。");
            return false;
        }
        var _nodeOfSelected = $("#" + sel);
        if (ref.get_type(_nodeOfSelected) === "trash") {
            showModal(330, 140, '系统信息', '', null, null, 4, "不能删除回收站。");
            return false;
        }
        showModal(333, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？', thisPage.OnDelete);
    },
    //删除操作
    OnDelete: function () {
        var instance = {};
        instance['departmentId'] = $("#id").val();

        $.ajax({
            type: "POST",
            url: urlDelete,
            timeout: 30 * 1000,
            data: JSON.stringify(instance),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            if (data > 0) {
                // 删除树形节点
                var sel = $.jstree.reference('treeContent').get_selected()[0];
                $.jstree.reference('treeContent').delete_node(sel);

                // 删除成功后，清空右侧表单内容
                thisPage.ClearForm();
                $("#OperateMode").html("");
                $('#ParentDeptName').text("");

                $('#id').val("0");
            }
        }).fail(function (data) {
            parent.ajaxError(data, 1);
        }).always(function () {
        });
    },
    ClearForm: function () {
        // 清空表单内容，准备下一个记录
        $(':input', '#form01').not(':button, :submit, :reset, :hidden')
                .val('').removeAttr('checked').removeAttr('selected');
        $('#mainForm')[0].reset();
        $("#mainForm").validate().resetForm();
        $(".error").removeClass("error");
        $(".tooltip").remove();
        $("img.errMsgTooltip").remove();
    }
};

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    setWndTitle('部门信息编辑');
    setViewPosition('<span>基础信息</span>部门信息编辑');

    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    var h = $(window).height();
    var w = $(window).width();

    $("#treeArea").css({width: 250, left: 8, height: h - 130});
    $("#tb-field").css({width: w - 8 - 265});
    $("#tb-field textarea").css({'max-width': w - 16 - 82});
    over = 1;
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$(function () {
    $("#mainForm").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _OrderNo: "required",
            _DepartmentName: "required"
        },
        messages: {
            _OrderNo: "请填写部门编码。",
            _DepartmentName: "请填写部门。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: parent.showErrors  //使用自定义的错误显示方法
    });
});
